//
//  ZTMapView.m
//  DianYing5
//
//  Created by uskr on 15/7/17.
//  Copyright (c) 2015年 uskr. All rights reserved.
//

#import "ZTMapView.h"

#import "LocationButton.h"

@interface ZTMapView ()<MAMapViewDelegate,CLLocationManagerDelegate,UIGestureRecognizerDelegate,AMapSearchDelegate>

@end

@implementation ZTMapView

-(UIView*)initWithFrame:(CGRect)rect withCenterLatitude:(CGFloat)latitude withCenterlongitude:(CGFloat)longitude
{
    
    self = [super initWithFrame:rect]; 


    if(self)
    {
        [self addMapViewWithCenterLatitude:latitude withCenterlongitude:longitude];
        
        //使从父类继承的协议对象(即代理对象)指向子类，在子类中实现父类的协议方法
        self.delegate = self;
        
        //初始化search对象
        self.search = [[AMapSearchAPI alloc] initWithSearchKey:@"9bb1c8b3662389e53bbb228d2e6b098e" Delegate:self];

    }

    return self;
}

-(void)addMapViewWithCenterLatitude:(CGFloat)latitude withCenterlongitude:(CGFloat)longitude
{
    self.mapType = MAMapTypeStandard;
    
    self.showTraffic = YES;
    
    CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
    
    location = [location locationMarsFromEarth];
    NSLog(@"mapView.centerCoordinate = %f:%f",location.coordinate.latitude, location.coordinate.longitude);

    self.centerCoordinate = location.coordinate ;
    
    self.zoomLevel = 16.5;
    
    // 设置显示级别
    //min=1.381543 max=20.000000
   // NSLog ( @"min=%f max=%f" ,   _mapView.minZoomLevel , _mapView.maxZoomLevel);
    
    
#pragma mark 在这里创建longPress管理对象
    UILongPressGestureRecognizer *longPress = [[ UILongPressGestureRecognizer alloc ] initWithTarget:self action:@selector(dealLongPress:)];
    longPress.delegate = self ;
    [self addGestureRecognizer:longPress];
    
#pragma mark 在这里创建定位管理对象
    _locationManager = [[CLLocationManager alloc]init];
    _locationManager.delegate = self;
    
#pragma mark//BLOCK:在CLLocationManager刚创建好时,这里调用block对MAMapView对象和CLLocationManager对象做额外设置
    if(_mapViewAndLocationManager)
        _mapViewAndLocationManager(self, _locationManager);
    
    if(![CLLocationManager locationServicesEnabled] == YES)
        return;
    
    [_locationManager requestAlwaysAuthorization];
    
}

//授权发生改变时回调
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    
    if (status == kCLAuthorizationStatusAuthorizedAlways)
    {
        // 设置定位
        self.showsUserLocation = YES ;

        self.userTrackingMode = MAUserTrackingModeFollowWithHeading;
        
    }
    
    if(self.locationManagerAndStatus)
        self.locationManagerAndStatus(manager, status);
    
}

-(void)dealLongPress:(UILongPressGestureRecognizer*)longPress
{
    //NSLog(@"按钮长按发生");
    if(longPress.state == UIGestureRecognizerStateBegan)
    {
        //点击位置 长按点在view中的位置
        CGPoint point = [longPress locationInView:self];
        //将point转换为地图中的经纬位置
        CLLocationCoordinate2D coordinate = [self convertPoint :point toCoordinateFromView:self];
        // 创建图钉标记,加入地图
        MAPointAnnotation *annotation = [[MAPointAnnotation alloc]init];
        annotation.coordinate = coordinate;
        annotation.title = @"地图标记" ;
        annotation.subtitle = [NSString stringWithFormat : @"loc=%f %f" ,coordinate.latitude, coordinate.longitude ];
        [self addAnnotation:annotation];
    }
}

-(BOOL)gestureRecognizer:( UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:( UIGestureRecognizer *)otherGestureRecognizer
{
    return YES ;
}

//创建图钉标记的回调
-(MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if([annotation isKindOfClass:[MAUserLocation class]])
    {
        return nil;
    }
    
    static NSString *annotationId = @"id";
    //创建图钉被点击后的视图, 先从一个池中获取
    MAPinAnnotationView *pin = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationId];
    
    if(pin == nil)
    {
        //如果池中不存在就创建一个
        pin = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationId];
    }
    
    pin.canShowCallout = YES;
    pin.animatesDrop = YES;
    
    //__weak ZTMapView* wkSelf = self;
    
    //在view中添加一个按钮,并添加点击后的方法
    LocationButton * button = [[LocationButton alloc]initWithFrame:CGRectMake(0, 0, 80, 44) withTitle:@"按钮" withBackgroundColor:nil withAction:^(LocationButton *button)
    {
        //构造AMapNavigationSearchRequest 导航路径对象，配置查询参数
        AMapNavigationSearchRequest *naviRequest= [[ AMapNavigationSearchRequest alloc] init];
        naviRequest.searchType = AMapSearchType_NaviWalking ;
        //naviRequest.requireExtension = YES;
        naviRequest.origin = [AMapGeoPoint locationWithLatitude:self.userLocation.coordinate.latitude longitude:self.userLocation.coordinate.longitude ];
        
        naviRequest.destination = [AMapGeoPoint locationWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
        
        //发起路径搜索
        [self.search AMapNavigationSearch:naviRequest];
        
        NSLog(@"%f  %f  ",annotation.coordinate.latitude, annotation.coordinate.longitude);
    }];
    
    pin.rightCalloutAccessoryView = button;
    return pin;
}

// 实现路径搜索的回调函数
- ( void )onNavigationSearchDone:(AMapNavigationSearchRequest *)request response:(AMapNavigationSearchResponse *)response
{
    
    // 获取方案列表
    NSLog ( @"共有%ld条路径可选" ,response.route.paths.count );
    AMapPath *path = [response.route.paths firstObject ];
    NSLog(@"第一条路径共有%ld个拐点",path.steps.count);
    
//    // 导航路段 AMapStep 数组
//    for (AMapStep *step in path.steps) {
//        NSLog ( @"%@ tast:%lds points:%@" ,step.instruction ,step.duration ,step.polyline );
//    }
    NSString * pointStr = [[NSString alloc]init];
    for(AMapStep *step in path.steps)
    {
        pointStr = [NSString stringWithFormat:@"%@;%@",pointStr,step.polyline];
    }

    NSArray * pointsArr = [pointStr componentsSeparatedByString:@";"];
    //NSLog(@"%@",pointsArr);
    
    //折线数据对象
    CLLocationCoordinate2D commonPolylineCoords[pointsArr.count-1];
    for(int i = 1; i < pointsArr.count; i++)
    {
        NSArray * point = [pointsArr[i] componentsSeparatedByString:@","];
        NSString * latitude = point[1];
        NSString * longtitude = point[0];
        commonPolylineCoords[i-1].latitude = latitude.floatValue;
        commonPolylineCoords[i-1].longitude = longtitude.floatValue;
    }
    
    //NSLog(@"%f %f",commonPolylineCoords[0].latitude,commonPolylineCoords[0].longitude);
    
    //构造折线视图对象
    MAPolyline *commonPolyline = [MAPolyline polylineWithCoordinates:commonPolylineCoords count:pointsArr.count-1];
    
    //在地图上添加折线对象
    [self addOverlay: commonPolyline];
    
    /*
     if(response.route == nil)
     {
     return;
     }
     
     // 通过 AMapNavigationSearchResponse 对象处理搜索结果
     NSString *route = [NSString stringWithFormat:@"Navi: %@", response.route];
     NSLog(@"%@", route);
     */
}

-(MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id <MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineView *polylineView = [[MAPolylineView alloc] initWithPolyline:overlay];
        polylineView.lineWidth = 4.0f;
        polylineView.strokeColor = [UIColor colorWithRed:0 green:0 blue:1 alpha:0.6];
        polylineView.lineJoin = kCGLineJoinRound;//连接类型 polylineView.lineCapType = kMALineCapRound;//端点类型
        return polylineView;
    }
    return nil;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
